<?php

class CStoreCategoryList {
	/**
	 *
	 * @var CStoreCategoryList
	 */
	static $instance;
	var $categories;
	var $parent_map;
	static $allCate;

	/**
	 *
	 * @return CStoreCategoryList
	 */
	public static function &getInstance() {
		if (!isset(self::$instance)) {
			self::$instance = new CStoreCategoryList();
		}
		return self::$instance;
	}

	public function __construct() {
		// Make file cache
		$fileCache = CSystem::$form_cache_dir.'product-categories-'.portal()->id.'.php';
		if(DEBUG or !file_exists($fileCache)){
			$categorys = CTable('category')->select_all();
			$dataCate = array();
			foreach($categorys as $k => $v){
				$dataCate[strtolower($v['char_seo'])] = $v;
			}
			$dataCate = var_export($dataCate, 1);
			$cache = '<?php return '.$dataCate.';?>';
			file_put_contents($fileCache, $cache);
		}			
		self::$allCate = require_once($fileCache);		
		
		$cache_name = 'categories_cache'.portal()->id;
		if (DEBUG or !@(list($this->categories, $this->parent_map) = CSystem::$cachedata->get($cache_name))) {			
			//$this->categories = CTable('cats/cat/cats/cat')->change_store(new CDataXmlStore(DATA_DIR.portal()->id.'/product_categories.xml','/root/'))->select_all();
			$this->categories = $this->getStructCategory($this->getListChildren(0));			
			$this->parent_map = array();
			if(count($this->categories) > 0){
				foreach($this->categories as $key=>$category) {
					$this->parent_map[$key] = $key;
					if (isset($category['cats']) and !empty($category['cats'])) {	
						foreach ($category['cats'] as $subcategory) {
							$this->parent_map[$subcategory['id']] = $key;
						}
					}
				}
			}
			CSystem::$cachedata->set($cache_name, array($this->categories, $this->parent_map), 6000);
		}
		
		
		
	}

	public function getRootCategory($category_id) {
		return @$this->parent_map[$category_id];
	}

	public function &getCategories(){
		return $this->categories;
	}
	
	// Khoanb Edit 13.08.09
	
	public function getListChildren($idParent = 0, $field = ''){
		$aListChildren = array();
		if(isset(self::$allCate)){
			foreach(self::$allCate as $k => $v){
				if($idParent == $v['parent_id']){
					if(empty($field)){
						$aListChildren[] = $v;
					}else{
						if(is_string($field)) $aListChildren[] = $v[$field];
						if(is_array($field)){
							foreach($field as $vField){
								$aListChildren[$k][$vField] = $v[$vField];
							}
						}
					}
				}
			}
		}
		return $aListChildren;
	}
	
	public function getParentCate($idChildren = 0){
		$parentCate = array();
		if(is_string($idChildren)){
			if(isset(self::$allCate[strtolower($idChildren)])){
				$cateChildren = self::$allCate[strtolower($idChildren)];
				foreach(self::$allCate as $v){
					if($cateChildren['parent_id'] == $v['id']){
						$parentCate = $v;
					}
				}
				
			}
		}
		if(is_int($idChildren)){
			foreach(self::$allCate as $v){
				if($idChildren == $v['id']){
					$parentCate = $v;
				}
			}
		}
		return $parentCate;
	}
	
	public function getStructCategory($data = array()){
		$aStructCategory = array();
		if(count($data) > 0){
			foreach($data as $k => $v){
				$setKey = $k;
				if($v['parent_id'] == 0){
					$setKey = $v['char_seo'];
				}
				$aStructCategory[$setKey] = array(
					'id' => $v['char_seo'],
					'idCate' => $v['id'],
					'name' => $v['name'],
					'status' => $v['status'],
					'description' => $v['description'],
					//'is_homepage' => $v['feature'],
					'is_homepage' => $v['status'],
					'image' => $v['image'],
					'original_id' => $v['char_seo'],
				);
				if($aChildren = $this->getListChildren($v['id']) and count($aChildren) > 0){					
					$cats = $this->getStructCategory($aChildren);
					$aStructCategory[$setKey] += array('cats' => $cats);
				}				
			}
		}
		return $aStructCategory;
	}
	
	/**
	 * Get all category in table category
	 *
	 * @param null
	 * @return array allCate
	 */
	
	public function getAllCate(){
		return self::$allCate;	
	}
	
	public function getNextCharCate($code = ''){
		if(!empty($code)) return substr($code, 0, strlen($code)-1).chr(ord(substr($code, -1, 1))+1);
	}
	
	/**
	 * Get all category in table category
	 *
	 * @param string $category_id
	 * @return array getOneRowsCate
	 */
	
	public function getOneRowsCate($category_id = '', $fields = ''){
		$category_id = strtolower($category_id);
		if(!empty($category_id) and isset(self::$allCate[$category_id])){
			if(!$fields){
				$objCate = self::$allCate[$category_id];
			}else{
				if(is_string($fields)){
					$objCate = self::$allCate[$category_id][$fields];
				}
				if(is_array($fields)){
					$objCate = array();
					foreach($fields as $v){
						if(isset(self::$allCate[$category_id][$v])){
							$objCate += array($v => self::$allCate[$category_id][$v]);
						}
					}
				}
			}
			return $objCate;
		}
	}
	
	/**
	 * Get condition for table product from category_id
	 *
	 * @param  string  $category_id
	 * @return object CExpression
	 */ 
	
	public function conditionCategory($category_id = ''){
		if(!empty($category_id) and isset(self::$allCate[strtolower($category_id)])){
			$codeCurrent = $this->getOneRowsCate($category_id, 'code');
			$nextCateChar = $this->getNextCharCate($codeCurrent);
			return EAnd(EGTE('cate_id', $codeCurrent), ELT('cate_id', $nextCateChar));
		}else{
			return array();
		}
	}
	
	/**
	 * Get html Option category not root
	 *
	 * @param  array  $data
	 * @param  int  $idSel (Default : 0)
	 * @param  string  $getColum (Default : id)
	 * @param  string  $sept(Default: --)
	 * @return string $sListCategory
	 */ 
	
	public function getListCategory($data = array(), $idSel = 0, $getColum = 'id', $sept = '--'){
		$sListCategory = '';
		if(count($data) > 0){
			foreach($data as $k => $v){
				$sel = '';
				if($idSel == $v['id']) $sel = ' selected = "selected" ';
				$sListCategory .= "<option value={$v[$getColum]} {$sel}>{$sept}{$v['name']}</option>\n";
				$sListCategory .= $this->getListCategory($this->getListChildren($v['id']), $idSel, $getColum, $sept.'--');
			}
		}
		return $sListCategory;
	}
	
	/**
	 * Get html Option category + root html
	 *
	 * @param  int  $idSel (Default : 0)
	 * @param  string  $getColum (Default : id)
	 * @param  string  $optionRoot (Default : <option value="0">Danh mục gốc</option>)
	 * @param  string  $sept(Default: --)
	 * @return string html Option Category
	 */ 
	
	public function htmlListOptionCategory($idSel = 0, $getColum = 'id', $optionRoot = '<option value="0">Danh mục gốc</option>', $sept = ''){
		return $optionRoot.$this->getListCategory($this->getListChildren(0), intval($idSel), $getColum);
	}
		
	public function getFilePropertyCategory($category_id = '', $path = ''){
		if(!empty($category_id)){
			if($path == '') $path = DATA_DIR.'default/product_categories/';
			$file_name = $path.$category_id.'.xml';
			//DATA_DIR.'default/product_categories/'.$parent_cat.'.xml';
			if(CFile::exists($file_name)) return $file_name;
			else{
				$aParent = $this->getParentCate($category_id);
				if(isset($aParent['char_seo'])){
					$this->getFilePropertyCategory($aParent['char_seo'], $path);	
				}else{
					//echo $category_id.'<br />';
					return $path.'root.xml';;
				}
			}
		}		
	}
	
	public function getDataTreeCategory($idCate = 0){
		if($items = $this->getListChildren($idCate) and count($items)){
			foreach($items as $k => $v){
				
			}
		}
	}
	
	public function getCatePath($category_id = '', &$result = ''){
		if(empty($result)){
			$result .= '.'.$category_id.'.';
		}else {
			$result .= $category_id.'.';
		}
		$detail = $this->getParentCate($category_id);
		if(!isset($detail['char_seo'])){
			return $result;
		}else {
			return $this->getCatePath($detail['char_seo'], $result);
		}
	}
	
	static function delCacheCategory(){
		$fileCache = CSystem::$form_cache_dir.'product-categories-'.portal()->id.'.php';
		if(CFile::exists($fileCache)) {
			unlink($fileCache);
		}
	}
	
}
?>